package com.blogs.message;

import com.rabbitmq.client.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @Author: xiaokai
 * @Description:
 * @Date: 2019/5/30
 * @Version: 1.0
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Consumer {

    @Test
    public void Consumer() throws Exception {

        //1 创建一个ConnectionFactory 并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("129.204.172.12");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2、通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        //3、通过connection创建一个Channel
        Channel channel = connection.createChannel();

        //4、声明（创建）一个队列
        String queueName = "test001";
        channel.queueDeclare(queueName, true, false, false, null);

        //5、创建一个消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        //6、设置channel
        channel.basicConsume(queueName, true, queueingConsumer);

        while (true) {
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.err.println("消费端： " + msg);
//            Envelope envelope = delivery.getEnvelope();
//            envelope.
        }
    }
}
